
//
// 120615 - AH - Created.
// 120713 - AH - Took CE_ID in use.
//

package org.soekrat.server.servlets.tools;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.japril.servlet.HttpRequestDef;
import org.soekrat.engine.SoekratEngine;
import org.soekrat.environment.Orb;
import org.soekrat.environment.OrbSuppliers;
import org.soekrat.server.io.db.ConversationElement;
import org.soekrat.server.io.db.SoekratDAO;
import org.soekrat.server.io.db.SoekratDAOFactory;
import org.soekrat.server.servlets.AbstractSoekratHttpServlet;
import org.soekrat.server.servlets.chat.OrbFactory;

@SuppressWarnings("serial")
public final class ShowPitHttpServlet extends AbstractSoekratHttpServlet 
{
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public ShowPitHttpServlet(){}
  
  @Override
  protected void handleRequest(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException 
  {
    HttpRequestDef def=getHttpRequestDef();
    
    if (!hasParameters(req))
    {
      PrintWriter pw=printSimpleHtmlStart(res);
      pw.println(def.compileApiHtml());
      printSimpleHtmlEnd(pw);
    }
    else
    {
      if (!validate(res, def, req)) return;
      
      SoekratDAO dao=new SoekratDAOFactory().create();
      
      long ceId=def.fetch(CE_ID.name(), req).getLongValue();
      
      ConversationElement ce=dao.getConversationElement(ceId);
      if (ce==null)
      {
        respond(res, "Did not find ConversationElement in database for key : "
          +ceId);
      }
      
      Orb orb=new OrbFactory().create(ce);
      OrbSuppliers suppliers=getOrbSuppliers();
      String err=suppliers.supply(orb);
      if (err!=null)
      {
        respond(res, err);
        return;
      }
      
      @SuppressWarnings("unused")
      SoekratEngine engine=(SoekratEngine)orb.getAttribute("soekrat-engine");
      
      //Pit pit=engine.getPit();
      //String txt=pit.toString();
      
      res.setContentType("text/plain");
      PrintWriter pw=res.getWriter();
      //pw.println(txt);
      pw.flush();
    }
  }

  @Override
  public HttpRequestDef getHttpRequestDef() 
  {
    return new HttpRequestDef("/soekrat_server/pit_inspection")
      .desc("Pit Inspection").parameter(CE_ID);
  }
  
}
